export const readPGMFile = async (url:string) => {
  const response = await fetch(url);
  const buffer = await response.arrayBuffer();
  const data = new Uint8Array(buffer);
  // 解析PGM头部信息
  let offset = 0;
  let headerStr = "";
  // 检查魔数（P5）
  if (String.fromCharCode(data[0], data[1]) !== "P5") {
    throw new Error("Invalid PGM file format");
  }
  offset = 2;

  // 跳过注释和空白字符
  while (offset < data.length) {
    if (data[offset] === 35) {
      // # 注释
      while (data[offset] !== 10 && data[offset] !== 13) offset++;
    } else if (
      data[offset] === 32 ||
      data[offset] === 10 ||
      data[offset] === 13
    ) {
      // 空格、换行
      offset++;
    } else {
      break;
    }
  }

  // 读取宽度
  while (data[offset] >= 48 && data[offset] <= 57) {
    headerStr += String.fromCharCode(data[offset++]);
  }
  const width = parseInt(headerStr, 10);
  if (isNaN(width)) throw new Error("Invalid width in PGM file");
  headerStr = "";

  // 跳过空白字符
  while (data[offset] === 32 || data[offset] === 10 || data[offset] === 13)
    offset++;

  // 读取高度
  while (data[offset] >= 48 && data[offset] <= 57) {
    headerStr += String.fromCharCode(data[offset++]);
  }
  const height = parseInt(headerStr, 10);
  if (isNaN(height)) throw new Error("Invalid height in PGM file");

  // 跳过空白字符
  while (data[offset] === 32 || data[offset] === 10 || data[offset] === 13)
    offset++;

  // 读取最大值
  headerStr = "";
  while (data[offset] >= 48 && data[offset] <= 57) {
    headerStr += String.fromCharCode(data[offset++]);
  }
  const maxVal = parseInt(headerStr, 10);
  if (isNaN(maxVal)) throw new Error("Invalid max value in PGM file");

  // 跳过最后的空白字符
  while (data[offset] === 32 || data[offset] === 10 || data[offset] === 13)
    offset++;

  // 提取图像数据
  const imageData = new Uint8Array(width * height);
  for (let i = 0; i < width * height; i++) {
    imageData[i] = data[offset + i];
  }
  return { width, height, data: imageData };
};

export function handleCreateCanvas(res:any){
  // 创建 canvas 元素来处理 PGM 数据
  const tempCanvas = document.createElement("canvas");
  tempCanvas.width = res.width;
  tempCanvas.height = res.height;
  const ctx:any = tempCanvas.getContext("2d");

  // 创建 ImageData 对象
  const imageData = ctx.createImageData(res.width, res.height);
  for (let i = 0; i < res.data.length; i++) {
    const value = res.data[i];
    // 设置 RGB 值（灰度图像，所以 R=G=B）
    imageData.data[i * 4] = value; // R
    imageData.data[i * 4 + 1] = value; // G
    imageData.data[i * 4 + 2] = value; // B
    imageData.data[i * 4 + 3] = 255; // Alpha
  }
  // 将 ImageData 绘制到临时 canvas
  ctx.putImageData(imageData, 0, 0);
  return tempCanvas;
}

export function handlePgmParser(buffer:any){
  const pgmData:any = readPGMFile(buffer)
  const canvas = document.createElement('canvas')
  canvas.width = pgmData.width
  canvas.height = pgmData.height
  const ctx = canvas.getContext('2d')
  const imageData = ctx?.createImageData(pgmData.width, pgmData.height) ?? new ImageData(pgmData.width, pgmData.height)
  // 填充灰度数据（PGM 为单通道，需转为 RGBA）
  for (let i = 0; i < pgmData.data.length; i++) {
    const value = pgmData.data[i]
    imageData.data[i * 4] = value     // R
    imageData.data[i * 4 + 1] = value // G
    imageData.data[i * 4 + 2] = value // B
    imageData.data[i * 4 + 3] = 255   // A
  }
  ctx?.putImageData(imageData, 0, 0)
  const pngUrl:any = canvas.toDataURL('image/png')
  // 在 LeaferJS 中加载
  const image = new Image(pngUrl)
} 
